package practice_bank;

public class CoupleWithdrawDemo2 {
    public static void main(String[] args) throws InterruptedException {
        // 创建共享账户，初始余额10万元
        JointAccount account = new JointAccount(100000);

        System.out.println("========== 同步代码块测试 ==========");
        testWithdraw(account, "withdrawWithSyncBlock");

        System.out.println("\n========== 同步方法测试 ==========");
        testWithdraw(account, "withdrawWithSyncMethod");

        System.out.println("\n========== Lock锁测试 ==========");
        testWithdraw(account, "withdrawWithLock");
    }

    private static void testWithdraw(JointAccount account, String methodName) throws InterruptedException {
        // 创建两个取款线程
        Thread xiaoMing = new Thread(() -> {
            try {
                JointAccount.class.getMethod(methodName, double.class, String.class)
                        .invoke(account, 100000, "小明");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        Thread xiaoHong = new Thread(() -> {
            try {
                JointAccount.class.getMethod(methodName, double.class, String.class)
                        .invoke(account, 100000, "小红");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        // 启动线程
        xiaoMing.start();
        xiaoHong.start();

        // 等待两个线程结束
        xiaoMing.join();
        xiaoHong.join();

        // 打印最终余额
        System.out.println("最终账户余额: " + account.getBalance() + "元");
    }
}